import json
import tkinter as tk
from tkinter import messagebox
import requests
from requests.adapters import HTTPAdapter
from hashlib import md5
import random


message_text = ""

# 创建一个函数，用于更新提示消息
def update_message(message):
    global message_text
    message_text = message
    message_label.config(text=message_text)


requests.adapters.DEFAULT_RETRIES = 10

s = requests.session()
s.mount('http://', HTTPAdapter(max_retries=10))
s.mount('https://', HTTPAdapter(max_retries=10))
s.keep_alive = False

headers = {
    "os": "android",
    "appVersion": "40",
    "Sign": "Sign",
    "cl_ip": "192.168.1.3",
    "User-Agent": "okhttp/3.14.9",
    "Content-Type": "application/json;charset=utf-8"
}


def getMd5(text: str):
    return md5(text.encode('utf-8')).hexdigest()


def save(user, uid, token):
    url = 'http://sxbaapp.zcj.jyt.henan.gov.cn/interface/clockindaily20220827.ashx'

    longitude = user["longitude"]
    latitude = user["latitude"]
    if user["randomLocation"]:
        longitude = longitude[0:len(longitude) - 1] + str(random.randint(0, 10))
        latitude = latitude[0:len(latitude) - 1] + str(random.randint(0, 10))

    data = {
        "dtype": 1,
        "uid": uid,
        "address": user["address"],
        "phonetype": user["deviceType"],
        "probability": -1,
        "longitude": longitude,
        "latitude": latitude
    }
    headers["Sign"] = getMd5(json.dumps(data) + token)
    res = requests.post(url, headers=headers, data=json.dumps(data))

    if res.json()["code"] == 1001:
        return True, res.json()["msg"]
    return False, res.json()["msg"]


def getToken():
    url = 'http://sxbaapp.zcj.jyt.henan.gov.cn/interface/token.ashx'
    res = requests.post(url, headers=headers)
    if res.json()["code"] == 1001:
        return True, res.json()["data"]["token"]
    return False, res.json()["msg"]


def login(user, token):
    password = getMd5(user["password"])
    deviceId = user["deviceId"]

    data = {
        "phone": user["phone"],
        "password": password,
        "dtype": 6,
        "dToken": deviceId
    }
    headers["Sign"] = getMd5((json.dumps(data) + token))
    url = 'http://sxbaapp.zcj.jyt.henan.gov.cn/interface/relog.ashx'
    res = requests.post(url, headers=headers, data=json.dumps(data))

    try:
        return res.json()
    except json.JSONDecodeError:
        # 处理 JSON 解码错误
        print('用户', user['alias'], '登录账号失败，返回的响应内容无效')
        return {"code": -1, "msg": "返回的响应内容无效"}

def prepareSign(user):
    if not user["enable"]:
        print(user['alias'], '未启用打卡，即将跳过')
        return

    print('已加载用户', user['alias'], '即将开始打卡')

    headers["phone"] = user["deviceType"]

    res, token = getToken()
    if not res:
        print('用户', user['alias'], '获取Token失败')
        return

    loginResp = login(user, token)

    if loginResp["code"] != 1001:
        error_message = f"用户 {user['alias']} 登录账号失败，错误原因：{loginResp['msg']}"
        print(error_message)
        update_message(f"{user['alias']}, {loginResp['msg']}")  # 显示错误消息
        return



    uid = loginResp["data"]["uid"]
    resp, msg = save(user, uid, token)

    if resp:
        success_message = f"{user['alias']} 打卡成功！"
        print(success_message)
        update_message(success_message)  # 显示打卡成功消息
    else:
        failure_message = f"{user['alias']} 打卡失败"
        print(failure_message)
        update_message(failure_message)  # 显示打卡失败消息


def submit_request(entry_fields):
    users = []

    for i in range(0, len(entry_fields), 10):
        user = {
            "alias": entry_fields[i].get(),
            "phone": entry_fields[i + 1].get(),
            "password": entry_fields[i + 2].get(),
            "deviceType": entry_fields[i + 3].get(),
            "deviceId": entry_fields[i + 4].get(),
            "randomLocation": True if entry_fields[i + 5].get() == '1' else False,
            "address": entry_fields[i + 6].get(),
            "longitude": entry_fields[i + 7].get(),
            "latitude": entry_fields[i + 8].get(),
            "enable": True if entry_fields[i + 9].get() == '1' else False
        }
        users.append(user)

    with open("user.json", "w") as f:
        json.dump(users, f, indent=4)

    for user in users:
        if user["enable"]:
            prepareSign(user)

def create_input_fields(window):
    parameter_names = ["备注可空", "手机号", "密码", "设备类型", "设备id", "填1",
                       "打卡地址", "经度", "纬度", "填1"]

    entry_fields = []

    for i, param in enumerate(parameter_names):
        label = tk.Label(window, text=param)
        label.grid(row=i, column=0, sticky=tk.W, padx=6, pady=6)

        entry = tk.Entry(window)
        entry.grid(row=i, column=1, padx=6, pady=6)

        entry_fields.append(entry)


    submit_button = tk.Button(window, text="立即打卡", command=lambda: submit_request(entry_fields))
    submit_button.grid(row=len(parameter_names), column=0, columnspan=2, pady=10)

    return [entry_fields, submit_button, parameter_names]

def main():

    window = tk.Tk()
    window.title("职校家园免费打卡,更新群323874022")
    window.iconbitmap("C:\\Users\\Administrator\\Desktop\\职校家园免费打卡exe\\蘑菇icon.ico")

    window.geometry("500x450")

    [user_entries, submit_button, parameter_names] = create_input_fields(window)

    global message_label
    message_label = tk.Label(window, text="", fg="green")
    message_label.grid(row=len(parameter_names) + 2, column=0, columnspan=2, padx=6, pady=6)
    window.mainloop()


if __name__ == '__main__':

    main()
